#include "logdbmanager.h"
#include "../share/global.h"
#include "mainwindow.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QVariant>
#include <QDir>

QSqlError LogDbManager::lastError;

bool LogDbManager::createLogDb(bool recreate)
{
    QString logDbPath = mainWindow->getDbConfig().logPath;
    if (!QDir().mkpath(logDbPath)) return false;

    QSqlDatabase logdb = QSqlDatabase::addDatabase("QSQLITE", LOG_DB_CONNECTION_NAME);
    logdb.setDatabaseName(QString("%1/%2").arg(logDbPath, LOG_DB_NAME));
    if (logdb.open()) {
        if (recreate) {
            logdb.exec("DROP INDEX IX_LogTable_LogTime ON LogTable");
            logdb.exec("DROP TABLE LogTable");
        }
        logdb.exec("CREATE TABLE IF NOT EXISTS LogTable(LogTime TimeStamp NOT NULL DEFAULT(datetime(\'now\',\'localtime\')),"
                   "UserName VARCHAR(64), EventType VARCHAR(64), EventContent TEXT)");
        logdb.exec("CREATE INDEX IF NOT EXISTS IX_LogTable_LogTime ON LogTable(LogTime)");
    }

    lastError = logdb.lastError();
    return lastError.type()==QSqlError::NoError;
}

bool LogDbManager::insertMessageToDb(EventType type, const QString &msg)
{
    QSqlDatabase logdb = QSqlDatabase::database(LOG_DB_CONNECTION_NAME);
    QSqlQuery query(logdb);
    query.prepare("INSERT INTO LogTable(UserName, EventType, EventContent) VALUES(?,?,?)");
    query.addBindValue(mainWindow->getCurrentUser().name);
    if (type < ET_TypeCount) {
        query.addBindValue(mainWindow->getStringTables().EventTypeStringTable[type]);
        query.addBindValue(msg);
    } else {
        query.addBindValue(mainWindow->getStringTables().EventTypeStringTable[ET_SysError]);
        query.addBindValue(QObject::tr("Error while logging message: %1.").arg(msg));
    }
    query.exec();
    lastError = query.lastError();
    return lastError.type()==QSqlError::NoError;
}

bool LogDbManager::removeLogRecord()
{
    QSqlDatabase logdb = QSqlDatabase::database(LOG_DB_CONNECTION_NAME);
    QSqlQuery query(logdb);
    query.prepare("DELETE FROM LogTable WHERE LogTime<?");

    QDateTime time;
    switch (mainWindow->getDbConfig().logPeriod) {
    case LP_OneWeek:
        time = QDateTime::currentDateTime().addDays(-7);
        break;
    case LP_OneMonth:
        time = QDateTime::currentDateTime().addMonths(-1);
        break;
    case LP_OneYear:
        time = QDateTime::currentDateTime().addYears(-1);
        break;
    }

    bool ok = false;
    if (time.isValid()) {
        query.addBindValue(time.toString(SQLITE_DATETIME_FORMAT));
        ok = query.exec();
        lastError = query.lastError();
    }
    return ok;
}
